package com.lagou.zk;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.SQLException;

public class JdbcTest {
    static ZkClient zkClient = null;

    public static void main(String[] args) throws SQLException, InterruptedException {

        String zkPath = "/lg-zkClient/dbConfig";
//        获取zk连接
        zkClient = ZkUtils.getCon();
//        使用自定义序列化
        zkClient.setZkSerializer(new ZkStrSerializer());
//        创建zk节点并将常量文件中的数据库配置信息写入zk
        ZkUtils.createNode(zkClient,zkPath);
//        使用配置信息初始化数据库连接信息
        DataSource dataSource = DruidUtils.addConf(zkClient, zkPath);
//        执行查询
        DruidUtils.execQuery(dataSource,zkPath);
        Thread.sleep(3000);
//        ZkUtils.listen(zkClient,zkPath);

//        匿名内部类监听节点数据是否变化
        zkClient.subscribeDataChanges(zkPath, new IZkDataListener() {
            Logger logger = LoggerFactory.getLogger(JdbcTest.class);
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println(s + "    data is changed,new data   " + o);
//                配置信息变化，重新获取配置信息并执行查询
                DataSource dataSource = DruidUtils.addConf(zkClient, s);
                DruidUtils.execQuery(dataSource,s);
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                System.out.println(s + "is deleted!!!");
            }
        });

//      手动更新zk节点里的配置信息，用来触发监听器
        zkClient.writeData(zkPath,"jdbc:mysql://centos7-3:3306/azkaban?characterEncoding=UTF-8	hive	12345678");
        Thread.sleep(5000);

        zkClient.delete(zkPath);
        Thread.sleep(5000);
    }

}
